package com.example.himalaya;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.adapters.TrackListRvAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.interfaces.IAlbumDetailViewCallback;
import com.example.himalaya.interfaces.IPlayerViewCallback;
import com.example.himalaya.interfaces.ISubscriptionViewCallback;
import com.example.himalaya.presenters.AlbumDetailPresenter;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.presenters.SubPresenter;
import com.example.himalaya.utils.Constants;
import com.example.himalaya.utils.ImageBlur;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.views.RoundRectImageView;
import com.example.himalaya.views.UILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ms.square.android.expandabletextview.ExpandableTextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.ArrayList;
import java.util.List;

public class DetailActivity extends BaseActivity implements IAlbumDetailViewCallback, UILoader.OnRetryClickListener, TrackListRvAdapter.onTrackItemClickListener, IPlayerViewCallback, ISubscriptionViewCallback {

    private static final String TAG = "DetailActivity";

    private ImageView mLargeCover;
    private RoundRectImageView mSmallCover;
    private TextView mAlbumTitle;
    private ExpandableTextView mAlbumInfo;
    private AlbumDetailPresenter mAlbumDetailPresenter;

    private int mCurrentPage = 1;
    private RecyclerView mTrackRv;
    private TrackListRvAdapter mTrackListRvAdapter;
    private FrameLayout mTrackListContainer;
    private UILoader mUILoader;
    private Album mCurrentAlbum;
    private View mPlayControlContainer;
    private ImageView mPlayControlIv;
    private TextView mPlayControlTv;
    private PlayerPresenter mPlayerPresenter;

    private final static int DEFAULT_PLAY_INDEX = 0;
    private List<Track> mCurrentTracks = new ArrayList<>();
    private TwinklingRefreshLayout mRefreshLayout;
    private boolean mIsLoadMore = false;
    private Track mCurrentTrack;
    private TextView mDetailSubBtn;
    private SubPresenter mSubPresenter;
    private View mDetailSubBtnContainer;
    private TextView mAlbumAuthorTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
//        //设置顶部状态栏为透明颜色
//        getWindow().setStatusBarColor(Color.TRANSPARENT);
//        //隐藏状态栏，布局充满整个屏幕，状态icon图标在原状态栏位置现布局顶部显示
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        initView();

        initPresenter();

        updateSubState();
        updatePlayState(mPlayerPresenter.isPlaying());

        initEvent();
    }

    private void updateSubState() {
        if (mSubPresenter != null) {
            boolean isSub = mSubPresenter.isSub(mCurrentAlbum);
            mDetailSubBtn.setText(isSub?"取消订阅":"+ 订阅");
            LogUtil.d(TAG, "订阅状态-->" + isSub);
        }
    }

    private void initPresenter() {
        mAlbumDetailPresenter = AlbumDetailPresenter.getAlbumDetailPresenter();
        mAlbumDetailPresenter.registerViewCallBack(this);

        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallBack(this);

        mSubPresenter = SubPresenter.getSubPresenter();
        mSubPresenter.registerViewCallBack(this);
        mSubPresenter.getSubList();
    }


    private void initView() {
        mSmallCover = findViewById(R.id.iv_small_cover);
        mAlbumTitle = findViewById(R.id.tv_album_title);
        mAlbumInfo = findViewById(R.id.album_info_tv);
        mTrackListContainer = findViewById(R.id.album_track_list_container);
        if (mUILoader ==null) {
            mUILoader = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(container);
                }
            };
        }
        mUILoader.setOnRetryClickListener(this);
        mTrackListContainer.removeAllViews();
        mTrackListContainer.addView(mUILoader);
        mPlayControlContainer = findViewById(R.id.detail_play_control_container);
        mPlayControlIv = findViewById(R.id.detail_play_control_iv);
        mPlayControlTv = findViewById(R.id.detail_play_control_tv);
        mPlayControlTv.setSelected(true);
        mDetailSubBtn = findViewById(R.id.detail_sub_btn);
        mDetailSubBtnContainer = findViewById(R.id.detail_sub_btn_container);
        mAlbumAuthorTv = findViewById(R.id.album_author_tv);
    }

    private void initEvent() {
        mPlayControlContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter != null) {
                    //判断播放器是否有播放列表
                    if (mPlayerPresenter.hasPlayList()) {
                        handlePlayControl();
                    }else{
                        handleNoHasPlayList();
                    }
                }
            }
        });
        mUILoader.setOnRetryClickListener(new UILoader.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                if (mAlbumDetailPresenter != null) {
                    mAlbumDetailPresenter.getDetailedTrackList((int) mCurrentAlbum.getId(),mCurrentPage);
                }
            }
        });

        mDetailSubBtnContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSubPresenter != null) {
                    boolean isSub = mSubPresenter.isSub(mCurrentAlbum);
                    if (isSub) {
                        mSubPresenter.deleteSub(mCurrentAlbum);
                    } else {
                        mSubPresenter.addSub(mCurrentAlbum);
                    }
                }
            }
        });
    }

    private void handlePlayControl() {
        if (mPlayerPresenter.isPlaying()) {
            //如果现在的状态是正在播放的，那么就暂停
            mPlayerPresenter.pause();
        } else {
            //如果现在的状态是非播放的，那么就让播放器播放节目
            mPlayerPresenter.play();
        }
    }


    private void handleNoHasPlayList() {
        if (mPlayerPresenter != null) {
            mPlayerPresenter.setPlayList(mCurrentTracks,DEFAULT_PLAY_INDEX);
//            mPlayerPresenter.play();
        }
    }

    private View createSuccessView(ViewGroup container) {
        View successView = LayoutInflater.from(this).inflate(R.layout.item_activity_detail_track_list, container, false);
        mTrackRv = successView.findViewById(R.id.album_track_list_Rv);
        mRefreshLayout = successView.findViewById(R.id.refresh_layout);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mTrackRv.setLayoutManager(linearLayoutManager);
        mTrackListRvAdapter = new TrackListRvAdapter();
        mTrackListRvAdapter.setOnTrackItemClickListener(this);
        mTrackRv.setAdapter(mTrackListRvAdapter);
        mTrackRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = UIUtil.dip2px(view.getContext(),2);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 2);
                outRect.left=UIUtil.dip2px(view.getContext(),5);
                outRect.right=UIUtil.dip2px(view.getContext(),5);
            }
        });
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                BaseApplication.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DetailActivity.this, "刷新成功...", Toast.LENGTH_SHORT).show();
                        mRefreshLayout.finishRefreshing();
                    }
                }, 500);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                BaseApplication.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mAlbumDetailPresenter != null) {
                            mAlbumDetailPresenter.pullUpToLoadMore();
                            mIsLoadMore = true;
                        }
                    }
                }, 500);

            }
        });
        return successView;
    }

    @Override
    public void onLoadAlbumInformation(Album album) {
        mCurrentAlbum = album;
        //获取专辑详情的曲目列表数据
        mAlbumDetailPresenter.getDetailedTrackList((int) album.getId(), mCurrentPage);

        if (mLargeCover != null) {
            Picasso.with(this).load(album.getCoverUrlLarge()).into(mLargeCover, new Callback() {
                @Override
                public void onSuccess() {
                    //Picasso方式获取图片是异步的，所以要在成功后，并且不等于空的情况下设置模糊效果
                    Drawable drawable = mLargeCover.getDrawable();
                    if (drawable != null) {
                        //图片设置高斯模糊效果
                        ImageBlur.makeBlur(mLargeCover, DetailActivity.this);
                    }
                }

                @Override
                public void onError() {
                    LogUtil.d(TAG,"Picasso框架方式载入图片失败");
                }
            });

        }
        if (mSmallCover != null) {
            Picasso.with(this).load(album.getCoverUrlLarge()).into(mSmallCover);
        }
        if (mAlbumTitle != null) {
            mAlbumTitle.setText(album.getAlbumTitle());
        }
        if (mAlbumInfo != null) {
            if (album.getAlbumIntro() != null&&album.getAlbumIntro().length()!=0) {
                mAlbumInfo.setText("        "+ album.getAlbumIntro());
            }else {
                mAlbumInfo.setText("        "+"无简介内容");

            }
        }

        if (mAlbumAuthorTv != null) {
            mAlbumAuthorTv.setText(album.getAnnouncer().getNickname());
        }

    }

    @Override
    public void onLoadDetailedTrackList(List<Track> tracks) {
        if (mIsLoadMore&&mRefreshLayout!=null) {
            mRefreshLayout.finishLoadmore();
            mIsLoadMore = false;
        }


        if (tracks != null) {
            mCurrentTracks.clear();
            mCurrentTracks.addAll(tracks);
        }

        //更新/设置UI数据
        mTrackListRvAdapter.setTrackData(tracks);
        mUILoader.updateUIStatus(UILoader.UIStatus.SUCCESS);
    }

    @Override
    public void onLoadLoading() {
        mUILoader.updateUIStatus(UILoader.UIStatus.LOADING);
    }

    @Override
    public void onLoadNetworkError() {
        mUILoader.updateUIStatus(UILoader.UIStatus.NETWORK_ERROR);
    }

    @Override
    public void onLoadDataEmpty() {
        mUILoader.updateUIStatus(UILoader.UIStatus.EMPTY);
    }

    @Override
    public void onLoadMoreFinished(int size) {
        if (size > 0) {
            Toast.makeText(this, "成功加载" + size + "条节目", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "没有更多节目", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRefreshFinished(int size) {

    }

    @Override
    public void onRetryClick() {
        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.getDetailedTrackList((int)mCurrentAlbum.getId(),mCurrentPage);
            mAlbumDetailPresenter = null;
        }
    }

    @Override
    public void OnTrackItemClick(List<Track> tracks, int position) {
        //设置播放器数据
        PlayerPresenter playerPresenter = PlayerPresenter.getPlayerPresenter();
        playerPresenter.setPlayList(tracks,position);

        Log.d(TAG, "OnTrackItemClick: "+position);
        //跳转到播放器界面
        Intent intent = new Intent(this, PlayerActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.unRegisterViewCallBack(this);
            mAlbumDetailPresenter = null;
        }
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
        if (mSubPresenter != null) {
            mSubPresenter.unRegisterViewCallBack(this);
            mSubPresenter = null;
        }
    }

    /**
     * 根据播放状态修改图标和文字
     * @param playing 是否正在播放
     */
    private void updatePlayState(boolean playing) {
        if ((mPlayControlIv != null && mPlayControlTv != null)) {
            mPlayControlIv.setImageResource(playing ? R.drawable.selector_detail_pause : R.drawable.selector_detail_play);
            if (mCurrentTrack != null) {
                mPlayControlTv.setText(playing?mCurrentTrack.getTrackTitle():"点击播放");
            }
        }

    }

    @Override
    public void onPlayStart() {
       updatePlayState(true);
    }

    @Override
    public void onPlayPause() {
        updatePlayState(false);
    }

    @Override
    public void onPlayStop() {
        updatePlayState(false);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onTrackListUI(List<Track> tracks) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode currentMode) {

    }

    @Override
    public void onProgressChange(int currentProgress, int totalDuration) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdateUI(Track track, int index) {
        mCurrentTrack = track;
    }

    @Override
    public void onUpdatePlayListOrder(boolean isReverse) {

    }





    @Override
    public void onAddSub(boolean isSuccess) {
        if (isSuccess) {
            mDetailSubBtn.setText("取消订阅");
        }
    }

    @Override
    public void onDeleteSub(boolean isSuccess) {
        if (isSuccess) {
            mDetailSubBtn.setText("+ 订阅");
        }
    }

    @Override
    public void onGetSubList(List<Album> albums) {
        for (Album album : albums) {
            LogUtil.d(TAG,"album -->"+album.getAlbumTitle());
        }
    }

    @Override
    public void onSubFull() {
        Toast.makeText(this,"订阅数量不可以超过"+ Constants.MAX_SUB_COUNT,Toast.LENGTH_SHORT).show();
    }
}